<template>
  <div class="select">
    <div class="input-box">
      <input class="input" v-model="optionValue" :placeholder="'请选择'" type="text" />
      <el-icon v-show="show" @click="show = false" class="icon" size="12"><ArrowUp /></el-icon>
      <el-icon v-show="!show" @click="show = true" class="icon" size="12"><ArrowDown /></el-icon>
    </div>

    <CollapseTransition>
      <div v-show="show" class="options-box">
        <slot></slot>
      </div>
    </CollapseTransition>
  </div>
</template>

<script setup lang="ts">
  import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
  import { ref, provide } from 'vue'
  import CollapseTransition from './CollapseTransition'
  const show = ref(false)
  const emits = defineEmits(['update:modelValue'])
  const props = defineProps({
    modelValue: {
      type: String
    }
  })
  const optionValue = ref(props.modelValue)

  const getOptionsValue = (value: string) => {
    if (value) {
      optionValue.value = value
      emits('update:modelValue', value)
      show.value = false
    }
  }
  provide('getOptionsValue', getOptionsValue)

  const transitionStyle = '0.3s height ease-in-out'

  const Transition = {
    beforeEnter(el: any) {
      el.style.transition = transitionStyle
      el.style.height = '0'
      el.style.overflow = 'hidden'
    },

    enter(el: any) {
      // 强制重排以确保高度从0开始
      void el.offsetHeight

      if (el.scrollHeight !== 0) {
        el.style.height = `${el.scrollHeight}px`
      }
    },

    afterEnter(el: any) {
      el.style.transition = ''
      el.style.height = ''
      el.style.overflow = ''
    },

    beforeLeave(el: any) {
      // 获取当前实际高度
      el.style.height = `${el.scrollHeight}px`
      el.style.overflow = 'hidden'

      // 强制重排以确保高度变化被捕获
      void el.offsetHeight
    },

    leave(el: any) {
      if (el.scrollHeight !== 0) {
        el.style.transition = transitionStyle
        el.style.height = '0'
      }
    },

    afterLeave(el: any) {
      el.style.transition = ''
      el.style.height = ''
      el.style.overflow = ''
    }
  }
</script>

<style lang="scss" scoped>
  .select {
    width: 200px;
    .input-box {
      position: relative;
      margin-bottom: 5px;
      .input {
        width: 200px;
        height: 30px;
        border-radius: 5px;
        border: 1px solid #ccc;
      }
      .icon {
        position: absolute;
        top: 10px;
        right: 10px;
        cursor: pointer;
      }
    }
    .options-box {
      border: 1px solid #ccc;
      box-sizing: border-box; /* 关键：确保内边距不影响高度计算 */
      overflow: hidden; /* 关键：防止内容溢出影响动画 */
    }
    /* 进入和离开的过渡状态 */
    .fade-enter-active,
    .fade-leave-active {
      transition: all 1s ease;
    }

    .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
      height: 0;
    }
  }
</style>
